package com.et.core.util


import android.os.Looper
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding

class Adapter<T : Any, V : ViewBinding>(
    var call: (binding: V, t: T) -> Unit,
    var binding: (inflater: LayoutInflater, parent: ViewGroup) -> V
) : RecyclerView.Adapter<ViewHolder<V>>() {

    private var data: MutableList<T>? = null

    fun dispatchUpdate(result: DiffUtil.DiffResult, dest: MutableList<T>) {
        android.os.Handler(Looper.getMainLooper()).let {
            it.post {
                result.dispatchUpdatesTo(this)
                data = dest
            }
        }

    }

    override fun onBindViewHolder(holder: ViewHolder<V>, position: Int) {
        data?.let { call(holder.binding, it[position]) }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<V> {
        return ViewHolder(binding(LayoutInflater.from(parent.context), parent))
    }

    override fun getItemCount(): Int {
        return if (data == null) 0 else data!!.size
    }
}

class ViewHolder<T : ViewBinding>(var binding: T) : RecyclerView.ViewHolder(binding.root)
